import React from 'react';
import ReactDOM from 'react-dom';
import Dialog from './Dialog';

function getContainer(instance) {
  if (instance.props.getContainer) {
    return instance.props.getContainer();
  }
  const container = document.createElement('div');
  document.body.appendChild(container);
  return container;
}

export default class DialogWrap extends React.Component {
  static DefaultProps = {
    visible: false
  }

  constructor(props) {
    super(props);

    this.getComponent = this.getComponent.bind(this);
    this.removeContainer = this.removeContainer.bind(this);
    this.renderComponent = this.renderComponent.bind(this);
  }



  componentDidMount() {
    this.renderComponent(this);
  }

  shouldComponentUpdate({ visible }) {
    return !!(this.props.visible || visible);
  }

  componentDidUpdate() {
    this.renderComponent();
  }

  componentWillUnmount() {
    if (this.props.visible) {
      this.renderComponent(this, {
        afterClose: this.removeContainer,
        onClose() {
        },
        visible: false,
      });
    } else {
      this.removeContainer();
    }
  }

  getComponent(extra) {
    return (
      <Dialog
        {...this.props}
        {...extra}
        key="dialog"
      />
    );
  }

  isVisible() {
    return this.props.visible;
  }

  removeContainer() {
    if (this._container) {
      const container = this._container;
      ReactDOM.unmountComponentAtNode(container);
      container.parentNode.removeChild(container);
      this._container = null;
    }
  }

  renderComponent(instance, componentArg, ready) {
    if (!this.isVisible || this._component || this.isVisible(this)) {
      if (!this._container) {
        this._container = getContainer(this);
      }
      const component = this.getComponent(componentArg);
      const _this = this;
      ReactDOM.unstable_renderSubtreeIntoContainer(this,
        component, this._container,
        function callback() {
          _this._component = this;
          if (ready) {
            ready.call(this);
          }
        });
    }
  }

  render() {
    return (null);
  }
}
